var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var User = mongoose.model('User');
var Post = mongoose.model('Post');
var mock =require('../models/mock');
var checkAPIUser=require('../middleware/checkAPIUser');
var reprint =require('../middleware/reprint');
module.exports = router;

//全部用户
router.get('/users', function (req, res) {
  User.getAll(function (err, users) {
    if(err)return res.json({code:400,error:{message:'Bad Request'}});
    res.json({code:200,users:users});
  },true);
});

//当前用户信息和Post列表
router.get('/user/:name', function (req, res) {
  User.getByName(req.params.name,function (err, user) {
    if(err)return res.json({code:400,error:{message:'Bad Request'}});
    if(!user)return res.json({code:404,error:{message:'Not Found'}});

    var p=req.query.p?parseInt(req.query.p):1;
    var limit=2;
    Post.getPage({'user.name':user.name},p,limit,function (err, posts,total) {
      if(err)return res.json({code:400,error:{message:'查询博客列表错误',error:err}});
      res.json({code:200,user:user,post:posts,page:{curr:p,total:Math.ceil(total/limit)}});
    });

  },true);
});

//所有Post
router.get('/posts',function(req,res,next){
  var page=req.query.page?parseInt(req.query.page):1;
  var limit=2;
  Post.getPage(null,page,limit,function (err, posts,total) {
    if(err)return res.json({code:400,error:{message:'Bad Request'}});
    return res.json({
      code:200,
      posts:posts,
      page:{
        curr:page,
        total:Math.ceil(total/limit)
      }
    });
  });
});

//当前Post
router.get('/post/:id',function(req,res,next){
  Post.getById(req.params.id,function (err, post) {
    if(err)return res.json({'error':{code:400,message:'Bad Request'}});
    return res.json({
      code:200,
      post:post
    });
  });
});


//创建Post
router.post('/post',checkAPIUser,function (req, res, next) {
  var date=new Date(),body=req.body,user=req.user,post=new Post({
    title:body.title,
    tags:body.tags,
    content:body.content,
    desc:body.desc,
    user:{
      _id:user._id.toString(),
      name:user.name,
      email:user.email,
      face:user.face
    },
    date:date,
    time:mock.dateFormat(date,'all',true)
  });
  //console.log('new post:',post);
  post.save(function (err,newPost) {
    //console.log('new Post > save ret:',arguments);
    if(err)return res.json({code:400,error:{message:'Bad Request(save)'}});
    //console.log('new Post > ret:',newPost);
    res.json({coe:201,post:newPost});
  });
});

//编辑更新Post
router.patch('/post/:id',checkAPIUser,function (req, res, next) {
  Post.patch({_id:req.params.id,user:req.user,body:req.body},function (err,post) {
    //console.log('patch post ret:',ret);
    if(err)return res.json({code:400,error:{message:'Bad Request(mongodb)'}});
    if(!post)return res.json({code:400,error:{message:'Bad Request(no match)'}});
    res.json({code:200,post:post});
  });
});

//删除Post
router.delete('/post/:id',checkAPIUser,function (req, res, next) {
  Post.removePost({name:req.body.name,post_id:req.params.id}, function (err,ret) {
    if(err){
      return res.json({code:400,error:{message:err.message}});
    }
    res.json({code:204});
  });
});

//转载
router.post('/reprint',checkAPIUser,function(req,res,next){
  //console.log('reprint body:',req.body);
  req.params.username=req.user.name;
  req.params.post_id=req.body.post_id;
  next();
},reprint,function(req,res){
  var err=res.reprintResult.error;
  if (err) {
    if (err.yet) {//提示已经转载过该文章
      res.json({code:400,error:{message:'您已经转载过该文章-ErrA'}});
    } else {
      res.json({code:400,error:{message:err.message}});
    }
  }else{
   res.json({code:201,reprint:res.reprintResult.reprint});
  }
});

//搜索
router.get('/search',function (req, res, next) {
  //console.log('search body:',req.body);
  var keyword=req.query.keyword;
  var page=req.query.page?parseInt(req.query.page):1;
  var limit=2;
  Post.search(keyword,page,limit,function (err, posts,total) {
    if(err)return res.json({code:400,error:{message:err.message}});
    res.json({
      keyword:keyword,
      posts:posts,
      page:{
        curr:page,
        total:Math.ceil(total/limit)
      }
    });
  });
});

//分类归档
router.get('/archive', function (req, res) {
  Post.getArchive(function(err,list){
    //console.log('archive:',err,list);
    if(err)return res.json({code:400,error:{message:err.message}});
    res.json({code:200,list:list});
  });
});

//标签
router.get('/tags', function (req, res) {
  Post.getTags(function (err, tags) {
    if(err)return res.json({code:400,error:{message:'查询失败'}});
    console.log('tags:',tags);
    res.json({code:200,tags:tags});
  });
});

//当前标签下的Post列表
router.get('/tags/:tag', function (req, res) {
  var page=req.query.page?parseInt(req.query.page):1;
  var limit=2;
  Post.getPage({tags:{$in:[req.params.tag]}},page,limit,function(err,posts,total){
    console.log('tags/tag:',err,posts,total);
    if(err)return res.json({code:400,error:{message:'查询此标签下的博客失败'}});
    res.json({code:200,posts:posts,page:{
      curr:page,
      total:Math.ceil(total/limit)
    }});
  });
});

//添加评论
router.put('/comments',checkAPIUser, function (req, res) {
  var user=req.user;
  var comment={
    user:{_id:user._id,name:user.name,face:user.face,email:user.email},
    content:req.body.content,
    time:mock.dateFormat(new Date(),'all',true)
  };
  Post.addComment(req.body._id,comment,function (err,post) {
    if(err)return res.json({code:400,error:{message:'Bad Request'}});
    res.json({code:200,post:post});
  });
});